package com.hmall.pay.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.pay.constants.MQConstants;
import com.hmall.pay.domain.po.Order;
import com.hmall.pay.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

// 监听订单延迟消息（即利用死信交换机作为pay-service向trade-service发送的修改订单状态失效的兜底）
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    private final IOrderService orderService;
    private final PayClient payClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = MQConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MQConstants.DELAY_ORDER_KEY
    )
    )
    public void listenOrderDelayMessage(Long orderId) {
        // 1.查询订单
        Order order = orderService.getById(orderId);
        // 2.检测订单状态，判断是否已支付
        // 2.1订单不存在或已支付
        if(order == null || order.getStatus() != 1) {
            return;
        }
        // 2.2未支付，查询支付流水
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        // 3.检测支付流水状态，判断是否为已支付
        // 3.1 支付流水已支付
        if(payOrderDTO != null && payOrderDTO.getStatus() == 3) {
            orderService.markOrderPaySuccess(orderId);  // 修改订单状态为已支付
        } else {
            // 3.2未支付，修改订单状态为已取消，同时恢复库存
            orderService.cancelOrder(orderId);
        }

    }
}

